<?php
/**
 * 送审管理相关控制器:
 * 基础信息
 * 全局数据
 * 资料管理
 * 定案表管理
 * Created by PhpStorm.
 * User: ghost
 * Date: 2016/7/25
 * Time: 21:34.
 */
namespace Home\Controller;

use Home\Model\BaseInfoModel;
use Home\Model\VerdictModel;
use Think\Controller;

class SendController extends Controller
{
    /**
     * 基础信息.
     */
    public function basic($P = 1, $N = 10, $batch = '')
    {
        $where = '1';
        if (!empty($batch)) {
            $where = ['batch' => $batch];
        }

        $BaseInfoModel = new BaseInfoModel();
        $BasicInfos = $BaseInfoModel->where($where)->page($P, $N)->order('id desc')->select();
        $this->assign('projects', $BasicInfos);
        $this->assign('upload', _PHP_FILE_.'?s=Home/Info/importBaseInfo');
//        $this->assign('downBasic',__PUBLIC__.'/Templete/basicTemplete.xlsx');
        $total = intval($BaseInfoModel->where($where)->count() / $N) + 1;
        $this->assign('T', $total);
        $total = $total > 5 ? 5 : $total;
        $this->assign('total', $total);
        $urls = $this->getUrl();
        $this->assign('urls', $urls);
        $this->assign('batchList', $BaseInfoModel->getSomeBatchs());
        $this->assign('currentBatch', $batch);
        $this->assign('username', session('user_name'));
        $this->display();
    }

    /**
     * 全局数据.
     */
    public function all($P = 1, $N = 10, $batch = '')
    {
        $where = '1';
        if (!empty($batch)) {
            $where = ['batch' => $batch];
        }
// <<<<<<< HEAD
        $BaseInfoModel = new BaseInfoModel();
        $basicInfos = $BaseInfoModel->where($where)->page($P, $N)->order('id desc')->select();
        $project_codes = array_unique(array_column($basicInfos, 'project_code'));
        $boughts = $project_codes ? array_key_set(M('Bought')->where(['project_code' => ['in', $project_codes]])->select(), 'project_code', true) : [];
        $this->assign('batchList', $BaseInfoModel->getSomeBatchs());
        $this->assign('currentBatch', $batch);
//        数据核对
        $uids = [];
        foreach ($boughts as $bought) {
            $uids = $uids ? array_merge($uids, array_column($bought, 'uid')) : array_column($bought, 'uid');
        }
        $uids = array_unique($uids);
        $units = $uids ? M('Userinfo')->where(['uid' => ['in', $uids]])->getField('uid,company', true) : [];
        $UnitInfos = $uids ? array_key_set(M('Logdata')->where(['uid' => ['in', $uids]])->select(), 'uid') : [];
        $Datas = [];
        foreach ($basicInfos as $basicInfo) {
            $bought = array_key_set($boughts[$basicInfo['project_code']], 'type');
            if ($bought) {
                $diff = [];
                if ($basicInfo['tj_unit'] != $units[$bought['土建专业']['uid']]) {
                    $diff['tj'] = $units[$bought['土建专业']['uid']];
                }
                if ($basicInfo['jl_unit'] != $units[$bought['交流专业']['uid']]) {
                    $diff['jl'] = $units[$bought['交流专业']['uid']];
                }
                if ($basicInfo['pt_unit'] != $units[$bought['配套专业']['uid']]) {
                    $diff['pt'] = $units[$bought['配套专业']['uid']];
                }
                if ($basicInfo['tt_unit'] != $units[$bought['铁塔专业']['uid']]) {
                    $diff['tt'] = $units[$bought['铁塔专业']['uid']];
                }
                foreach ($bought as $Moudle) {
                    $unitdata = [
                        'unit' => $units[$Moudle['uid']],
                        'ecost' => $UnitInfos[$Moudle['uid']]['ecost'],
                        'ocost' => $UnitInfos[$Moudle['uid']]['ocost'],
                        'diff' => $UnitInfos[$Moudle['uid']]['diff'],
                        'diff_reason' => $UnitInfos[$Moudle['uid']]['diff_reason'],
                        'discription' => '',
                        'total' => $Moudle['singleprice'] * $Moudle['buynumber'],
                    ];
                    $detail[] = array_merge($Moudle, $unitdata);
                }
                $basicInfo['diff'] = $diff;
                $basicInfo['detail'] = array_key_set($detail, 'type');
                $Datas[] = $basicInfo;
            } else {
                $Datas[] = $basicInfo;
            }
        }
        $this->assign('Datas', $Datas);
        $urls = $this->getUrl();
        $this->assign('urls', $urls);
        $this->assign('username', session('user_name'));
// =======
        $BaseInfoModel=new BaseInfoModel();
        $logdataModel = D('Logdata');
        $basicInfos=$BaseInfoModel->where($where)->page($P,$N)->order('id desc')->select();

        $Datas = [];
        foreach ($basicInfos as $row) {
            $row['hasConflict'] = $BaseInfoModel->hasConflict($row['id']);
            $row['detail'] = [];
            $row['unitList'] = [];

            if (!$row['hasConflict']) {
                $row['detail'] = $BaseInfoModel->getDetailByProjectCode($row['project_code']);
            } else {
                $row['unitList'] = $BaseInfoModel->getUnitListByProjectCode($row['project_code']);
            }

            $Datas[] = $row;
        }

        $total=intval($BaseInfoModel->where($where)->count()/$N)+1;
        $this->assign('T',$total);
        $total=$total>5?5:$total;
        $this->assign('total',$total);

        $this->assign('Datas',$Datas);
        $urls=$this->getUrl();
        $this->assign('urls',$urls);
        $this->assign("username",session("user_name"));
        $this->assign('batchList', $BaseInfoModel->getSomeBatchs());
        $this->assign('currentBatch', $batch);
// >>>>>>> 6b99bf3fe76f249679ef74d55ae020456f14faf3
        $this->display('Send:all');
    }

    /**
     * 资料管理.
     */
    public function data($P = 1, $N = 10, $batch = '')
    {
        $where = '1';
        if (!empty($batch)) {
            $where = ['month' => $batch];
        }

        $DataView = D('DataView');
        $BasicInfos = $DataView->where($where)->page($P, $N)->order('id desc')->select();
        $this->assign('projects', $BasicInfos);
        $total = intval($DataView->where($where)->count() / $N) + 1;
        $this->assign('T', $total);
        $total = $total > 5 ? 5 : $total;
        $this->assign('total', $total);
        $urls = $this->getUrl();
        $this->assign('urls', $urls);
        $this->assign('batchList', $DataView->getSomeBatchs());
        $this->assign('currentBatch', $batch);
        $this->assign('username', session('user_name'));
        $this->display();
    }

    /**
     * 定案表管理.
     */
    public function verdict($P = 1, $N = 10, $batch = '')
    {
        $where = '1';
        if (!empty($batch)) {
            $where = ['month' => $batch];
        }

        $VerdictModel = new VerdictModel();
        $Datas = $VerdictModel->where($where)->page($P, $N)->order('id desc')->select();
        $this->assign('projects', $Datas);
        $total = intval($VerdictModel->where($where)->count() / $N) + 1;
        $this->assign('T', $total);
        $total = $total > 5 ? 5 : $total;
        $this->assign('total', $total);
//        $this->assign('downVerdict',__PUBLIC__.'/Templete/verdictTemplete.xlsx');
        $urls = $this->getUrl();
        $this->assign('urls', $urls);
        $this->assign('batchList', $VerdictModel->getSomeBatchs());
        $this->assign('currentBatch', $batch);
        $this->assign('username', session('user_name'));
        $this->display();
    }

    /**
     * 获取各方法入口的url.
     *
     * @return array
     */
    private function getUrl()
    {
        return [
            'basic' => _PHP_FILE_.'?s=Home/Send/basic',
            'all' => _PHP_FILE_.'?s=Home/Send/all',
            'data' => _PHP_FILE_.'?s=Home/Send/data',
            'verdict' => _PHP_FILE_.'?s=Home/Send/verdict',
        ];
    }

    /**
     * 删除操作.
     */
    public function delete()
    {
        $id = (int) $_POST['id'];
        if ($_POST['type'] == 'baseinfo') {
            $model = D('BaseInfo');
        } elseif ($_POST['type'] == 'verdict') {
            $model = D('Verdict');
        } else {
            exit;
        }

        if ($model->where(['id' => $id])->delete()) {
            $this->ajaxReturn([
                'code' => 'ok',
                'msg' => '删除成功',
                'data' => null,
            ]);
        } else {
            $this->ajaxReturn([
                'code' => 'fail',
                'msg' => '删除失败',
                'data' => null,
            ]);
        }
    }

    /**
     * 更新操作.
     */
    public function basemod($id)
    {
        $baseData = (new BaseInfoModel())->where(array('id' => I('get.id')))->find();
        $this->assign('id', I('get.id'));
        $this->assign('baseData', $baseData);
        $this->display();
    }

    public function vermod()
    {
        $verData = M('verdict')->where(array('id' => I('get.id')))->find();
        $this->assign('id', I('get.id'));
        $this->assign('verData', $verData);
        $this->display();
    }

    public function allmod()
    {
        $baseData = (new BaseInfoModel())->where(array('id' => I('get.id')))->find();
        $this->assign('id', I('get.id'));
        $this->assign('baseData', $baseData);
        $this->display();
    }
    public function update()
    {
        if (I('get.type') == 'base') {
            $params = array(
                'id' => I('post.id'),
                'batch' => I('post.batch'),
                'inner_check_time' => I('post.inner_check_time'),
                'amount_reply' => I('amount_reply'),
                'amount_design' => I('amount_design'),
                'zone' => I('post.zone'),
                'site_name' => I('post.site_name'),
                'project_code' => I('post.project_code'),
                'construction_type' => I('post.construction_type'),
                'category' => I('post.category'),
                'is_complete' => I('post.is_complete'),
                'description' => I('post.description'),
            );
            $rs = (new BaseInfoModel())->save($params);
        } elseif (I('get.type') == 'verdict') {
            $params = array(
                'id' => I('post.id'),
                'month' => I('post.month'),
                'city' => I('post.city'),
                'site_name' => I('post.site_name'),
                'project_code' => I('post.project_code'),
                'unit' => I('post.unit'),
                'profession' => I('post.profession'),
                'send_money' => I('post.send_money'),
                'verdict_money' => I('post.verdict_money'),
                'contract_money' => I('post.contract_money'),
                'sub_money' => I('post.sub_money'),
                'sub_rate' => I('post.sub_rate'),
            );
            $rs = M('verdict')->save($params);
        } elseif (I('get.type') == 'all') {
            $params = array(
                'id' => I('post.id'),
                'batch' => I('post.batch'),
                'inner_check_time' => I('post.inner_check_time'),
                'amount_reply' => I('amount_reply'),
                'amount_design' => I('amount_design'),
                'zone' => I('post.zone'),
                'site_name' => I('post.site_name'),
                'project_code' => I('post.project_code'),
                'construction_type' => I('post.construction_type'),
                'category' => I('post.category'),
                'is_complete' => I('post.is_complete'),
                'description' => I('post.description'),
                'tj_unit' => I('post.tj_unit'),
                'pt_unit' => I('post.pt_unit'),
                'jjg_unit' => I('post.jjg_unit'),
                'jl_unit' => I('post.jl_unit'),
            );
            $rs = (new BaseInfoModel())->save($params);
        }
        if ($rs) {
            if (I('get.type') == 'base') {
                $this->success('修改成功', U('Home/Send/basic'), 1);
            } elseif (I('get.type') == 'verdict') {
                $this->success('修改成功', U('Home/Send/verdict'), 1);
            } elseif (I('get.type') == 'all') {
                $this->success('修改成功', U('Home/Send/all'), 1);
            }
        } else {
            $this->error('没有被修改');
        }
    }

    /**
     * 导出excel.
     */
    public function exportExcel($param = [])
    {
        $type = $_POST['type'];
        $P = 1;
        $N = 10;
        $fileUrl = '';
        switch ($type) {
            case 'basic':
//                $P=1;
//                $N=10;
                $BasicInfos = (new BaseInfoModel())->where()->page($P, $N)->order('id desc')->select();
                $data = array_map(function ($v) {
                    return array_values($v);
                }, $BasicInfos);
                $name = iconv('UTF-8', 'GBK', '基础信息');
                $file = './Public/Excel/'.time().$name.'.xls';
                array_unshift($data, [
                    '序号', '项目批次', '内验结束时间', '批复金额', '设计金额', '所属区县', '立项站名', '项目编码', '建设方式', '分类', '土建单位', '工作量', '金加工单位', '工作量', '交流单位', '工作量', '配套单位', '工作量', '是否完工', '监理备注',
                ]);
                $fileUrl = $file;
                break;
            case 'all':
                $basicInfos = (new BaseInfoModel())->where()->page($P, $N)->order('id desc')->select();
                $data = array_map(function ($v) {
                    return array_values($v);
                }, $basicInfos);
                $name = iconv('UTF-8', 'GBK', '全局数据');
                $file = './Public/Excel/'.time().$name.'.xls';
                array_unshift($data, [
                    '序号', '项目批次', '内验结束时间', '批复金额', '设计金额', '所属区县', '立项站名', '项目编码', '建设方式', '分类', '土建单位', '工作量', '金加工单位', '工作量', '交流单位', '工作量', '配套单位', '工作量', '是否完工', '监理备注',
                ]);
                break;
            case 'data':
                $DataView = D('DataView');
                $BasicInfos = $DataView->where()->page($P, $N)->order('id desc')->select();
                $data = array_map(function ($v) {
                    return [
                        $v['id'],
                        $v['month'],
                        $v['site_name'],
                        $v['project_code'],
                        $v['profession'],
                        $v['unit'],
                        $v['send_money'],
                        $v['verdict_money'],
                        $v['contract_money'],
                        $v['is_submit_paper'],
                        $v['is_send_paper'],
                        $v['is_feedback_verdict'],
                        $v['is_send_verdict'],
                        $v['remark'],
                    ];
                }, $BasicInfos);
                $name = iconv('UTF-8', 'GBK', '资料管理');
                $file = './Public/Excel/'.time().$name.'.xls';
                array_unshift($data, [
                    '序号', '项目批次', '立项站点', '项目编码', '专业', '施工单位', '送审金额', '审定金额', '合同金额', '是否提交纸质资料', '是否寄送纸质材料', '是否反馈定案表', '是否寄送定案表', '备注',
                ]);
                $fileUrl = $file;
                break;
            case 'verdict':
                $VerdictModel = new VerdictModel();
                $Datas = $VerdictModel->where()->page($P, $N)->order('id desc')->select();
                $data = array_map(function ($v) {
                    return array_values($v);
                }, $Datas);
                $name = iconv('UTF-8', 'GBK', '定案表');
                $file = './Public/Excel/'.time().$name.'.xls';
                array_unshift($data, [
                    '序号', '月份', '所属城市', '站点名称', '项目编码', '专业', '送审金额', '审定金额', '合同金额', '审减金额', '审减率',
                ]);
                $fileUrl = $file;
                break;
        }

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.time().$name.'.xls');
        header('Cache-Control: max-age=0');

        write('php://output', ['sheet1' => $data]);
    }

    public function changeStuff()
    {
        $id = (int) $_POST['id'];
        $type = $_POST['type'];
        $value = $_POST['value'];

        if ($value == 'true') {
            $value = '是';
        }

        if ($value == 'false') {
            $value = '否';
        }

        $result = D('Stuff')->saveOne([
            'id' => $id,
            'verdict_id' => $verdict_id,
            $type => $value,
        ]);
        if ($result) {
            $this->ajaxReturn([
                'code' => 'ok',
                'msg' => '更新成功',
                'data' => null,
                'id' => $result,
            ]);
        } else {
            $this->ajaxReturn([
                'code' => 'fail',
                'msg' => '更新失败',
                'data' => null,
            ]);
        }
    }

    public function correct()
    {
        $id = (int) $_POST['id'];

        if (D('BaseInfo')->correct($id, [
            'tj_unit' => $_POST['tj_unit'],
            'pt_unit' => $_POST['pt_unit'],
            'jjg_unit' => $_POST['jjg_unit'],
            'jl_unit' => $_POST['jl_unit'],
        ])) {
            $this->ajaxReturn([
                'code' => 'ok',
                'msg' => '纠正成功',
                'data' => null,
            ]);
        } else {
            $this->ajaxReturn([
                'code' => 'fail',
                'msg' => '纠正失败',
                'data' => null,
            ]);
        }
    }

    public function emptyApply()
    {
        $projectCode = $_POST['code'];

        if (D('Logdata')->where(['project_code' => $projectCode])->delete()
            and D('Bought')->where(['project_code' => $projectCode])->delete()) {
            $this->ajaxReturn([
                'code' => 'ok',
                'msg' => '删除成功',
                'data' => null,
            ]);
        } else {
            $this->ajaxReturn([
                'code' => 'fail',
                'msg' => '删除失败',
                'data' => null,
            ]);
        }

    }
}
